package com.we.web.servlet;

import com.we.entity.ResultInfo;
import com.we.entity.User;
import com.we.service.CommentService;
import com.we.service.impl.CommentServiceImpl;
import com.we.util.JsonUtils;
import org.apache.commons.lang.StringUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description 评论请求处理
 * @Author cr7
 * @Date 2021-11-22 21:52
 * @Version V1.0
 */
@WebServlet("/comment")
public class CommentServlet extends BaseServlet {

    private ResultInfo info = new ResultInfo();
    private CommentService service = new CommentServiceImpl();

    //保存评论方法
    public void saveComment(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        User user = (User) req.getSession().getAttribute("user");
        String noteID = req.getParameter("noteID");
        String commentContent = req.getParameter("commentContent");
        if (user == null) {
            info.setFlag(false);
            info.setErrorMsg("当前用户未登录，请先登录");
            JsonUtils.writeValue(info, resp);
            return;
        }

        if (StringUtils.isBlank(noteID) || StringUtils.isBlank(commentContent)) {
            info.setFlag(false);
            info.setErrorMsg("评论失败");
            JsonUtils.writeValue(info, resp);
            return;
        }

        int count = service.saveComment(Integer.parseInt(noteID), user.getUserName(), commentContent, user.getNickname());
        if (count <= 0) {
            info.setFlag(false);
            info.setErrorMsg("评论失败");
        } else {
            info.setFlag(true);
        }

        JsonUtils.writeValue(info, resp);
    }
}
